#include "AvatarLuaLexer.h"
#include "../AvatarLibrary.h"

AvatarLuaLexer::AvatarLuaLexer(QObject *parent)
    : QsciLexerLua{parent}
{
    AvatarLibrary::avatar_register("__on_keyword", handleKeyword, this);
    const QString command = "for k,v in pairs(_G) do engine.execute('__on_keyword', k) if type(v)=='table' and k~='_G' then for b in pairs(v) do engine.execute('__on_keyword', k..'.'..b) end end end";
    AvatarLibrary::avatar_command(command);
    AvatarLibrary::avatar_update();
    keywordSet1 = keywordArray1.join(' ').toStdString();
    keywordSet2 = keywordArray2.join(' ').toStdString();
}

const char* AvatarLuaLexer::keywords(int set) const {
    if(set == 5) return keywordSet1.c_str();
    if(set == 6) return keywordSet2.c_str();
    return QsciLexerLua::keywords(set);
}

QStringList AvatarLuaLexer::autoCompletionWordSeparators() const
{
    QStringList wl;
    wl << "." << ":";
    return wl;
}

int AvatarLuaLexer::handleKeyword(int, const char** keyword, void* lexer)
{
    QString key = QString(keyword[0]);
    AvatarLuaLexer* luaLexer = static_cast<AvatarLuaLexer*>(lexer);
    if (key.endsWith("__")) return 0;
    else if (key.contains('.')) luaLexer->keywordArray2.append(key);
    else luaLexer->keywordArray1.append(key);
    return 1;
}
